package cn.virens.common.mybatis.mapper.example.base;

import cn.virens.common.util.exception.APIException;

import java.io.Serializable;
import java.util.Collection;

@SuppressWarnings("serial")
public abstract class AbstractExampleCriteria implements Serializable {
    public static final int TYPE_BETWEEN = 3;
    public static final int TYPE_SINGLE = 2;
    public static final int TYPE_LIST = 1;
    public static final int TYPE_NO = 0;

    private String condition;

    private Object value1;

    private Object value2;

    private String andOr;

    private int type;

    public AbstractExampleCriteria(String andOr, String condition) {
        this.condition = condition;
        this.type = TYPE_NO;
        this.andOr = andOr;
    }

    public AbstractExampleCriteria(String andOr, String condition, Object value1) {
        this.type = judgeType(value1);
        this.condition = condition;
        this.value1 = value1;
        this.andOr = andOr;
    }

    public AbstractExampleCriteria(String andOr, String condition, Object value1, Object value2) {
        this.condition = condition;
        this.type = TYPE_BETWEEN;
        this.value1 = value1;
        this.value2 = value2;
        this.andOr = andOr;
    }

    /**
     * 获取条件
     *
     * @return 条件
     */
    public String getCondition() {
        return condition;
    }

    /**
     * 设置条件
     *
     * @param condition 条件
     */
    public void setCondition(String condition) {
        this.condition = condition;
    }

    /**
     * 获取值1
     *
     * @return 值1
     */
    public Object getValue1() {
        return value1;
    }

    /**
     * 设置值1
     *
     * @param value1 值1
     */
    public void setValue1(Object value1) {
        this.value1 = value1;
    }

    /**
     * 获取值2
     *
     * @return 值2
     */
    public Object getValue2() {
        return value2;
    }

    /**
     * 设置值2
     *
     * @param value2 值2
     */
    public void setValue2(Object value2) {
        this.value2 = value2;
    }

    /**
     * 获取连接方式
     *
     * @return 连接方式
     */
    public String getAndOr() {
        return andOr;
    }

    /**
     * 设置连接方式
     *
     * @param andOr 连接方式
     */
    public void setAndOr(String andOr) {
        this.andOr = andOr;
    }

    /**
     * 验证当前条件是否有效
     *
     * @return 条件是否有效
     * @throws APIException 一般异常
     */
    public boolean isVerify() throws APIException {
        return condition != null && !condition.isEmpty();
    }

    /**
     * 获取当前条件匹配模式
     */
    public int getType() {
        return type;
    }

    /**
     * 设置当前条件匹配模式
     */
    public void setType(int type) {
        this.type = type;
    }

    /**
     * 判断当前值对应的数据类型
     *
     * @param value 值
     * @return 是否列表
     */
    private static int judgeType(Object value) {
        if (!(value instanceof Collection<?>)) {
            return TYPE_SINGLE;
        } else {
            return TYPE_LIST;
        }
    }
}
